"""MeetingClock module

Long usage message goes here
"""

import sys
import getopt
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from MeetingClockMainWindow import Ui_MeetingClock

class MeetingClock(QMainWindow, Ui_MeetingClock):
    """Implements a 'meeting clock', a visual display of the cost of a meeting.    
    """
    
    class Item():
        
        def __init__(self, cost, text, filename=None):
            self.cost = cost
            self.text = text
            self.filename = filename
    
    def __init__(self, app, *args):
        QMainWindow.__init__(self)

        # Set up the user interface from Designer.
        self.setupUi(self)
        
        # Hack to make up for bug in PyQt        
        sizePolicy = QSizePolicy(QSizePolicy.Policy(1),QSizePolicy.Policy(1))
        sizePolicy.setVerticalStretch(1)
        self.costGraphicsView.setSizePolicy(sizePolicy)
        
        self.initMenuBar()
        

        
        # Encapsulate widgets in lists
        self.attendeesSpinBoxes = [self.attendees1, self.attendees2, self.attendees3, self.attendees4, self.attendees5, self.attendees6, self.attendees7]
        self.rateLineEdits = [self.rate1, self.rate2, self.rate3, self.rate4, self.rate5, self.rate6, self.rate7]        
        
        # Connect up signals to sockets/methods
        for widget in self.attendeesSpinBoxes:
            app.connect(widget, SIGNAL("valueChanged(int)"),
                        self.updateRate)     
        
        for widget in self.rateLineEdits:
            app.connect(widget, SIGNAL("returnPressed()"),
                        self.updateRate)
        
        app.connect(self.startButton, SIGNAL("clicked()"),
                    self.start)
        
        app.connect(self.resetButton, SIGNAL("clicked()"),
                    self.reset)
        

        
        self.timer = QTimer()
        
        self.connect(self.timer, SIGNAL("timeout()"), self.showCost)
        
                
        self.timestep = 0.1     # How often cost is updated in seconds
        
        self.timer.start(self.timestep*1000)    # Frequency at which QTimer generates signals
        
        self.fullScreen = False
        
        self.text = "0.00"
        self.font = QFont()
        self.time = 0.0
        self.elapsedTime = 0.0
        self.running = False
        self.totalCost = 0.0
        self.displayItem = False
        
        self.rates = [50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0]
        self.attendees = [0, 0, 0, 0, 0, 0, 0]
        
        #self.keyCosts = [self.Item(2.00,"Boo!","vest.jpg"), self.Item(1.00,"Hello","beer.jpg")]
        
        self.keyCosts = self.readCosts()
        
        print self.keyCosts[0].filename
        
        
        # Overuse of list comprehensions for no goof reason
        [self.rateLineEdits[i].insert(str(self.rates[i])) for i in range(len(self.rateLineEdits))]
                
        self.updateRate()
        
        self.createScene()
        
        
    def updateRate(self):
        """Called when either the number of attendees or the hourly rate changes.        
        """
        #Query spinboxes for values
        self.attendees = [x.value() for x in self.attendeesSpinBoxes]
        #Query charge out rate lineEdits
        self.rates = [x.text().toDouble()[0] for x in self.rateLineEdits]
        self.totalRate = sum([self.rates[i]*self.attendees[i] for i in range(len(self.rates))])
        
        
    def showCost(self):
        if self.running:
            self.time += self.timestep
            self.totalCost += 0.1 * self.totalRate/3600.0
            
            # OK, this will change, but for now...
            # Loop through *ordered* list of items
            
            for item in self.keyCosts:
            
                if (self.totalCost > item.cost) and (self.totalCost < (item.cost + 0.2)):
                    self.displayItem = True
                    self.currentItem = item
                    self.lastItemTime = self.time
                    break
                
            
            if self.displayItem:
                
                if (self.time - self.lastItemTime) > 1.0:
                    self.displayItem = False
                    
                self.createScene(self.currentItem.text, self.currentItem.filename)
                
            else:
            
                self.text = "$%5.2f" % self.totalCost
                self.font = QFont()
                
                
                self.createScene()
                
            
    def start(self):
        self.running = True
        
    def pause(self):
        self.running = False
        
    def reset(self):
        self.totalCost = 0.0
        self.running = False
        self.showCost()
        
    def toggleFullScreen(self):
        self.setWindowState(self.windowState() ^ Qt.WindowFullScreen)    
        
    
    def about(self):
        QMessageBox.about(self, "About MeetingClock",
                          "Visit the project's <a href='http://code.google.com/p/meetingclock/'>Google Code homepage</a><br/>Copyright John Walley 2007")
        
    def help(self):
        QMessageBox.about(self, "Help",
                          "Visit the project's <a href='http://code.google.com/p/meetingclock/'>Google Code homepage</a><br/>Copyright John Walley 2007")

        
    def initMenuBar(self):
        self.connect(self.actionFullscreen,
                     SIGNAL("activated()"),
                     self.toggleFullScreen)        
        self.connect(self.actionAbout,
                     SIGNAL("activated()"),
                     self.about)
        self.connect(self.actionHelp,
                     SIGNAL("activated()"),
                     self.help)
        
    def createScene(self, text=None, filename=None):
    
        scene = QGraphicsScene()
        self.costGraphicsView.setScene(scene)
                    
        if text:
                       
            pixmap = QPixmap("Images/" + filename)
          
            item = QGraphicsPixmapItem(pixmap)  

            scene.addItem(item)
            
            item = scene.addText(text, self.font)

            item.scale(3.0,3.0)
            
        else:
        
            item = scene.addText(self.text, self.font)
            
            item.scale(10.0,10.0)
              
        
        self.scene = scene
        self.scene.update()
        
        
    def readCosts(self):
        """Reads in the costs of key items from costs.txt
        """

        keyCosts = []
        
        file = open('costs.txt')
        for line in file.readlines():
            item = line.split(',')
            # Remove endline character "\n"
            keyCosts.append(self.Item(float(item[0]), item[1], item[2][:-1]))
            
        return keyCosts
            
        
        
class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg        
   
        
def main(argv=None):
    # Allows agruments to be passed from interactive Python session
    if argv is None:
        argv = sys.argv
    
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
             raise Usage(msg)
        
        app = QApplication(args)
     
        app.connect(app, SIGNAL("lastWindowClosed()"),
                    app, SLOT("quit()"))  
     
        win = MeetingClock(app)   
            
        win.show()    
         
        app.exec_()        
        
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2
        
   
if __name__=="__main__":
    sys.exit(main())
